package com.edu.hbwe.book.dao.impl;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.edu.hbwe.book.dao.UserDao;
import com.edu.hbwe.book.entity.User;
import com.edu.hbwe.book.util.DbUtil;


public class UserDaoImpl implements UserDao{
	// 添加用户
	public void addUser(User user)   {
		String sql = "insert into user(username,password,gender,email,telephone,introduce,activecode) values(?,?,?,?,?,?,?)";
		QueryRunner runner = new QueryRunner(DbUtil.getDataSource());
		int row;
		try {
			row = runner.update(sql, user.getUsername(), user.getPassword(),
					user.getGender(), user.getEmail(), user.getTelephone(),
					user.getIntroduce(), user.getActiveCode());
			if (row == 0) {
				throw new RuntimeException();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	// 根据激活码查找用户
	public User findUserByActiveCode(String activeCode)   {
		String sql = "select * from user where activecode=?";
		QueryRunner runner = new QueryRunner(DbUtil.getDataSource());
		User user = null;
		try {
			user = runner.query(sql, new BeanHandler<User>(User.class), activeCode);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}

	// 激活用戶
	public int activeUser(String activeCode)   {
		String sql = "update user set state=? where activecode=?";
		QueryRunner runner = new QueryRunner(DbUtil.getDataSource());
		int row =0;
		try {
			row = runner.update(sql, 1, activeCode);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return row;
	}
	
	//根据用户名与密码查找用户
	public User findUserByUsernameAndPassword(String username, String password)   {
		String sql="select * from user where username=? and password=?";
		QueryRunner runner = new QueryRunner(DbUtil.getDataSource());
		User user = null;
		try {
			user = runner.query(sql, new BeanHandler<User>(User.class),username,password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}

}
